#include "tserver.h"
#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <algorithm>
namespace tlib
{
	TServer::TServer()
	{

	}

	TServer::~TServer()
	{

	}
#define IO_THREAD_COUNT	1
#define BS_THREAD_COUNT 32
	void TServer::Start(char* host, int port)
	{
		serSock_.Listen(host, port);
		if (serSock_.SetReuseAddr(true)) log_exit("Server SetReuseAddr Error");
		if (serSock_.SetReusePort(true)) log_exit("Server SetReusePort Error");
		ioThreadPool_.Start(IO_THREAD_COUNT);
		bsThreadPool_.Start(BS_THREAD_COUNT);
		for (int i = 0; i < IO_THREAD_COUNT; i++)
			ioThreadPool_.Run(std::bind(&TEventLoop::RunLoop, &eventLoop_[i], this));
		while (true)
		{
			TSocket* cli = serSock_.Accept();
			//if (!cli->SetNonBlock(true)) log_exit("Client SetNonBlock Error");
			cli->SetNonBlock(true);
			OnConn(cli);
			eventLoop_[cli->fd() % IO_THREAD_COUNT].AddLoop(cli);
		}
	}

	long long recvTimes = 0;
	void TServer::PreRecv(TSocket* sock)
	{
		int len = sock->WriteBuffer(BLOCK_SIZE);
		recvTimes++;
		if (recvTimes % 100000 == 0) log_debug("recvTimes: %lld", recvTimes);
		if (len > 0)
		{
			bsThreadPool_.Run(std::bind(&TServer::OnRecv, this, sock));
		}
		else if (len == 0)
		{
		}
		else
		{
			OnClose(sock);
			eventLoop_[sock->fd() % IO_THREAD_COUNT].DelLoop(sock);
			sock->Close();
		}
	}
}